import { useEffect, useState } from 'react'
import axios from '../utils/axios'
import { Space, Table, Form, Input, Button, message, Modal } from 'antd';
import type { TableProps } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
type FieldType = {
	title?: string;
	tag?: string;
};
type FieldTypeModal = {
	title?: string;
	content?: string;
}
interface DataType {
	id: number;
	key: string;
	name: string;
	age: number;
	address: string;
	tags: string[];
}
const Server = () => {
	const columns: TableProps<DataType>['columns'] = [
		{
			title: '标题',
			dataIndex: 'title',
			key: 'title',
		},
		{
			title: '内容',
			dataIndex: 'content',
			key: 'content',
		},
		{
			title: '创建时间',
			dataIndex: 'createdAt',
			key: 'createdAt',
		},
		{
			title: '结束时间',
			dataIndex: 'updatedAt',
			key: 'updatedAt',
		},
		{
			title: '操作',
			key: 'action',
			render: (_, record) => (
				<Space size="middle">
					<span style={{ color: 'blue' }} onClick={() => editHandle(record)}><EditOutlined color='blue' />编辑</span>
					<span style={{ color: 'red' }} onClick={() => delHandle(record.id)}><DeleteOutlined color='red' />删除</span>
				</Space>
			),
		},
	];
	const [form] = Form.useForm()
	const [data, setData] = useState([])
	const [page, setPage] = useState(1)
	const [count, setCount] = useState(0)
	const [pageSize, setPageSize] = useState(10)
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [isState, setIsState] = useState(true)
	const [id, setId] = useState(null)
	const getArticleList = async (title?: string, tag?: string) => {
		const res = await axios.get('/article/list', {
			params: {
				page,
				pageSize,
				keyword: title,
				tag
			}
		})
		// console.log(res)
		const { data, status } = res
		if (status === 200) {
			setCount(data.count)
			setData(data.rows)
		}
	}
	useEffect(() => {
		getArticleList()
	}, [page, pageSize])
	// 分页
	const changeHandel = (page: number, pageSize: number) => {
		setPage(page)
		setPageSize(pageSize)
	}
	// 搜索
	const onFinish = (values: FieldType) => {
		// console.log(values)
		const { title } = values
		setPage(1)
		getArticleList(title)
	}
	// 重置
	const resetHandle = () => {
		getArticleList()
	}
	// 删除
	const delHandle = async (id: number) => {
		// console.log(id)
		const res = await axios.delete(`/article/${id}`, { params: { article: id } })
		// console.log(res)
		const { status } = res
		if (status === 204) {
			message.success('删除成功')
			getArticleList()
		}
	}
	// modal
	const handleOk = () => {
		setIsModalOpen(false);
	};
	const handleCancel = () => {
		setIsModalOpen(false);
	};
	// 新增
	const addHaandle = () => {
		setIsState(true)
		setIsModalOpen(true)
		form.resetFields()
	}
	// 编辑
	const editHandle = (record: any) => {
		// console.log(record.id)
		setIsState(false)
		setIsModalOpen(true)
		form.setFieldsValue(record)
		setId(record.id)
	}
	// 点击新增编辑
	const handleAddAndEditonFinish = async (values: any) => {
		// 新增
		if (isState) {
			const res = await axios.post('/article', {
				title: values.title,
				content: values.content,
				authorId: 47529555
			})
			console.log(res)
			const { status } = res
			if (status === 200) {
				console.log(1)
				getArticleList()

			}
		}
		// 编辑
		else {
			const res = await axios.put(`/article/${id}`, values)
			console.log(res)
			const { status } = res
			if (status === 204) {
				message.success('编辑成功')
				getArticleList()
			}
		}
		setIsModalOpen(false)
	}
	return (
		<div>
			<div>
				<Form
					name="basic"
					labelCol={{ span: 8 }}
					layout='inline'
					wrapperCol={{ span: 12 }}
					style={{ maxWidth: 800 }}
					initialValues={{ remember: true }}
					onFinish={onFinish}
					autoComplete="off"
				>
					<Form.Item<FieldType>
						label="标题"
						name="title"
					>
						<Input />
					</Form.Item>
					<Form.Item<FieldType>
						label="标签"
						name="tag"
					>
						<Input />
					</Form.Item>
					<Form.Item label={null}>
						<Button type="primary" htmlType="submit">
							搜索
						</Button>

					</Form.Item>
					<Form.Item label={null}>
						<Button htmlType="reset" onClick={() => resetHandle()}>
							重置
						</Button>
					</Form.Item>
					<Form.Item label={null}>
						<Button type="primary" onClick={() => addHaandle()}>
							新增
						</Button>
					</Form.Item>
				</Form>
			</div>
			<Table<DataType> rowKey='id' columns={columns} dataSource={data}
				pagination={{
					total: count,
					showSizeChanger: true,
					onChange: changeHandel,
					showQuickJumper: true,
					showTotal: (total) => `共 ${total} 条`,
				}}
			/>
			<Modal
				title={isState ? '新增' : '编辑'}
				closable={{ 'aria-label': 'Custom Close Button' }}
				okText='确定'
				cancelText='取消'
				open={isModalOpen}
				onOk={handleOk}
				onCancel={handleCancel}
			>
				<Form
					form={form}
					// name="basic"
					labelCol={{ span: 6 }}
					wrapperCol={{ span: 24 }}
					style={{ maxWidth: 700 }}
					initialValues={{ remember: true }}
					onFinish={handleAddAndEditonFinish}
					autoComplete="off"
				>
					<Form.Item<FieldType>
						label="标题"
						name="title"
					>
						<Input />
					</Form.Item>
					<Form.Item<FieldTypeModal>
						label="内容"
						name="content"
					>
						<Input />
					</Form.Item>
					<Form.Item label={null}>
						<Button type="primary" htmlType="submit">
							{isState ? '添加' : '保存'}
						</Button>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	)
}

export default Server